<?php

namespace api\common\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii\filters\RateLimitInterface;
use api\common\models\Common;
use api\modules\v1\models\Code;
use api\modules\v1\models\Category;

class User extends Common implements IdentityInterface
{
    public $re_pwd = '';
    public $old_pwd = '';
    public $password = '';
    public $code = '';
    public $phone_new = '';

    public $type = '';
    public $openid = '';

    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;

    /**
     * @inheritdoc
     */
    # 设置table
    public static function tableName()
    {
        return '{{%user_app}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    # 设置 status  默认  ，以及取值的区间
    public function rules()
    {
        return [
            ['username', 'required','message'=>'{attribute}不能为空', 'on' => ['create']],
            ['username', 'filter', 'filter' => 'trim', 'on' => ['create']],
            [['username'],'match','pattern'=>'/^[a-zA-z0-9]{4,20}$/','message'=>'{attribute}必须为4-20位字母数字或组合', 'on' => ['create']],
            ['username', 'unique', 'targetClass' => 'api\common\models\User','filter'=>['status'=>self::STATUS_ACTIVE], 'message' => '用户名已被占用', 'on' => ['create']],

            [['password','re_pwd'], 'required','message'=>'{attribute}不能为空', 'on' => ['create','pwd','forget']],
            [['password','re_pwd'], 'filter', 'filter' => 'trim', 'on' => ['create','pwd','forget']],
            [['password'], 'string', 'min' => 6,  'max' => 20,'message'=>'必须为6-20位', 'on' => ['create','pwd','forget']],

            [['old_pwd','re_pwd'], 'required','message'=>'{attribute}不能为空', 'on' => ['pwd']],
            [['old_pwd','re_pwd'], 'filter', 'filter' => 'trim', 'on' => ['pwd']],
            [['old_pwd'], 'string', 'min' => 6,  'max' => 20,'message'=>'必须为6-20位', 'on' => ['pwd']],
            ['old_pwd', 'validateOldPassword', 'on' => ['pwd']],

            ['re_pwd', 'compare', 'compareAttribute' => 'password', 'message' => '两次密码输入必须一致', 'on' => ['create','pwd','forget']],

            [['phone'],'required','message'=>'{attribute}不能为空', 'on' => ['create','phone']],
            [['phone'], 'unique','filter'=>['status'=>self::STATUS_ACTIVE],'message'=>'{attribute}已经被占用了', 'on' => ['create','phone']],
            [['phone'], 'filter', 'filter' => 'trim', 'on' => ['create','phone']],
            [['phone'],'match','pattern'=>'/^1[34578]{1}\d{9}$/','message'=>'{attribute}格式不正确', 'on' => ['create','phone']],

            [['phone_new'],'required','message'=>'{attribute}不能为空', 'on' => ['phone']],
            [['phone_new'], 'filter', 'filter' => 'trim', 'on' => ['create','phone']],
            [['phone_new'],'match','pattern'=>'/^1[34578]{1}\d{9}$/','message'=>'{attribute}格式不正确', 'on' => ['phone']],


            [['nickname'],'required','message'=>'{attribute}不能为空', 'on' => ['nickname']],
           // [['nickname'], 'unique','filter'=>['status'=>self::STATUS_ACTIVE],'message'=>'{attribute}已经被占用了', 'on' => ['create','nickname']],

            /**
            [['email'],'required','message'=>'{attribute}不能为空', 'on' => ['create']],
            [['email'], 'unique','filter'=>['status'=>self::STATUS_ACTIVE],'message'=>'{attribute}已经被占用了', 'on' => ['create']],
            [['email'], 'filter', 'filter' => 'trim', 'on' => ['create']],
            [['email'],'email','message'=>'{attribute}格式不正确', 'on' => ['create']],
            **/

            //[['head_img'], 'safe', 'on' => ['create','headimg']],
            [['head_img'], 'required','message'=>'{attribute}不能为空', 'on' => ['headimg']],
            [['head_img'], 'validateHead', 'on' => ['headimg']],

            ['status', 'default', 'value' => self::STATUS_ACTIVE, 'on' => ['create']],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED], 'on' => ['create']],


            //第三方登录验证
            ['type', 'safe', 'on' => ['create']],
            ['type', 'in', 'range' => ['qq','wx','wb'], 'on' => ['create']],
            ['openid', 'safe', 'on' => ['create']],
            ['type', 'validateType', 'on' => ['create']],

            [['code'], 'required','message'=>'{attribute}不能为空', 'on' => ['create','phone','forget','withdraw','withdrawpass','withdraw']],
            [['code'], 'filter', 'filter' => 'trim', 'on' => ['create','phone','forget','withdraw','withdrawpass','withdraw']],
            [['code'], 'validateCode', 'on' => ['create','phone','forget','withdraw','withdrawpass','withdraw']],
            //绑定提现帐户
            [['withdraw_zfb','withdraw_wx'], 'string', 'on' => ['withdraw']],
            //设置提现密码
            [['withdraw_password'], 'required','message'=>'{attribute}不能为空', 'on' => ['withdrawpass']],
            [['withdraw_password'], 'filter', 'filter' => 'trim', 'on' => ['withdrawpass']],
            ['withdraw_default', 'integer', 'on' => ['withdrawdefault']],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', '序号'),
            'username' => Yii::t('app', '账号'),
            'nickname' => Yii::t('app', '昵称'),
            'auth_key' => Yii::t('app', 'Auth Key'),
            'password_hash' => Yii::t('app', '密码'),
            'password' => Yii::t('app', '密码'),
            're_pwd' => Yii::t('app', '确认密码'),
            'old_pwd' => Yii::t('app', '旧密码'),
            'password_reset_token' => Yii::t('app', 'Password Reset Token'),
            'email' => Yii::t('app', '邮箱'),
            'status' => Yii::t('app', '状态'),
            'created_at' => Yii::t('app', '添加时间'),
            'updated_at' => Yii::t('app', '修改时间'),
            'phone'=>Yii::t('app', '手机号码'),
            'phone_new'=>Yii::t('app', '新手机号码'),
            'code'=>Yii::t('app', '验证码'),
            'head_img'=>Yii::t('app', '头像'),
            'is_false'=>Yii::t('app', '账号'),
            'withdraw_zfb'=>Yii::t('app', '支付宝账号'),
            'withdraw_wx'=>Yii::t('app', '微信账号'),
            'withdraw_password'=>Yii::t('app', '提现密码'),
            'withdraw_default'=>Yii::t('app', '提现默认帐户'),
        ];
    }

    /**
     * @inheritdoc
     */
    # 通过id 找到identity
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    # 通过access_token 找到identity
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token, 'status' => self::STATUS_ACTIVE]);
    }

    # 生成access_token
    public function generateAccessToken()
    {
        $this->access_token = Yii::$app->security->generateRandomString();
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
       // return static::find()->where('(`username` = "'.$username.'" or `phone` = "'.$username.'") and status = '.self::STATUS_ACTIVE)->one();
        return static::find()->where('(`username` = "'.$username.'" or `phone` = "'.$username.'") and status != 0')->one();
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    # 此处是忘记密码所使用的
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }


    /*
     * 用户注册
     * @return bool|null
     */
    public function signup()
    {
        if ($this->validate()) {
            $this->setPassword($this->password);
            $this->generateAuthKey();
            $this->status = self::STATUS_ACTIVE;
            //$this->status = 9;
            $this->created_at = date('Y-m-d H:i:s',time());
            $this->updated_at = date('Y-m-d H:i:s',time());
            $this->access_token = $this->makeAccessToken($this->username,$this->password);
            if ($this->save(false)) {
                return true;
            }
        }
        return null;
    }

    public function signup_tmp($phone,$pwd)
    {
        $this->isNewRecord = true;
        $this->password = $pwd;
        $this->username = $phone;
        $this->phone = $phone;
        $this->setPassword($this->password);
        $this->generateAuthKey();
        $this->is_false = 1;
        $this->status = self::STATUS_ACTIVE;
        $this->created_at = date('Y-m-d H:i:s',time());
        $this->updated_at = date('Y-m-d H:i:s',time());
        $this->access_token = $this->makeAccessToken($this->username,$this->password);
        $this->save() && $this->id=0;
    }

    /*
     * 忘记密码
     * @return bool|null
     */
    public function forget(){
        if ($this->validate()) {
            $this->setPassword($this->password);
            $this->generateAuthKey();
            $this->updated_at = date('Y-m-d H:i:s',time());
            $this->access_token = $this->makeAccessToken($this->username,$this->password);
            if ($this->save(false)) {
                return true;
            }
        }
        return null;
    }

    /*
     * 生成加密字符串
     * @param $username
     * @param $password
     * @return string
     */
    public function makeAccessToken($username,$password){
        return md5($username.Yii::$app->params['access_token_seeds'].$password);
    }

    /*
     * 验证 验证码
     * @param $attribute
     * @param $params
     * @return bool
     */
    public function validateCode($attribute, $params)
    {
        $Code = new Code();
        $data = $Code->validateCode($this->phone,$this->code);
        if($data['success'] == false){
            $this->addError($attribute, $data['msg']);
            return false;
        }
        return true;
    }

    /*
     * 头像base64解码并本地化
     * @param $attribute
     * @param $params
     * @return bool
     */
    public function validateHead($attribute, $params){
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $this->head_img, $result)){
            $type = $result[2];
            $file_name = './uploads/head_img/'.uniqid(Yii::$app->user->identity->id.'_').'.'.$type;
            if (file_put_contents($file_name, base64_decode(str_replace($result[1], '', $this->head_img)))){
                $this->head_img = self::ftp_upload(substr($file_name,1),$file_name,1);
                return true;
            }
        }else{
            $this->addError($attribute, '图片解析失败');
            return false;
        }
    }

    public function validateType($attribute, $params){
        $openid_field = $this->type.'_openid';
        $this->$openid_field = $this->openid;
        unset($this->type);
        unset($this->openid);
    }

    /*
     * 修改手机
     * @return bool|null
     */
    public function phone()
    {
        if($this->validate()) {
            if($this->phone_new == $this->phone){
                $this->addError($this->phone_new, '新手机号码不可与旧手机号码相同');
                return false;
            }
            $this->phone = $this->phone_new;
            if ($this->save(false)) {
                return true;
            }
        }
        return null;
    }


    /*
     * 修改密码时 验证旧密码
     * @param $attribute
     * @param $params
     * @return bool
     */
    public function validateOldPassword($attribute, $params)
    {
        if(!Yii::$app->security->validatePassword($this->old_pwd, Yii::$app->user->identity->password_hash)){
            $this->addError($attribute, "旧密码错误.");
            return false;
        }elseif($this->old_pwd == $this->password){
            $this->addError($attribute, "新密码不能于旧密码相同.");
            return false;
        }
        return true;
    }

    /*
     * 获取用户列表
     * @param $id
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getList($id){
        $_data =  self::find()->select('id,username,nickname,phone,email,head_img,status,created_at,updated_at,access_token')->where('id in ('.$id.')')->asArray()->all();

        $ImgBaseUrl = self::getImgBaseUrl();
        foreach($_data as $key => $value){
            if($value['head_img'] !=''){
                $_data[$key]['head_img'] = $ImgBaseUrl.substr($value['head_img'],1);
            }
        }
        return $_data;
    }

    /*
     * 获取当前用户信息
     * @return array|null|ActiveRecord
     */
    public function getInfo(){
        $_data =  self::find()->select('id,username,nickname,phone,email,head_img,status,created_at,updated_at,access_token,qq_openid,wx_openid,wb_openid,is_authentication,collect_category')->where('id = '.Yii::$app->user->identity->id)->asArray()->one();
        $ImgBaseUrl = self::getImgBaseUrl();
        if($_data['head_img'] !=''){
            $_data['head_img'] = $ImgBaseUrl.substr($_data['head_img'],1);
        }
        //$Category = new Category();
        //$_data['collect_category'] = $Category->getId2Info($_data['collect_category']);
        return $_data;
    }

    public function beforeSave($insert = true)
    {
        if (!$this->isNewRecord) {
            $this->updated_at = date('Y-m-d H:i:s',time());
        }
        return true;
    }
}
